const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");

const app = express();
const upload = multer({
  dest: path.resolve(__dirname, "./uploads"),
  fileFilter: function (req, file, cb) {
    console.log(file, "-file-");

    // 定义允许上传的文件格式
    const allow = ["image/jpeg", "image/png"];
    cb(null, allow.includes(file.mimetype));
  },
});

app.use(express.static(path.resolve(__dirname, "./public")));

/**
 * 上传头像
 *  请求地址：/xxx
 *  请求方式：POST
 *  请求参数：
 *      avatar: 图片
 *
 *  响应参数：
 *    {
 *      code: 0,
 *      msg: '上传成功',
 *      data: '文件可以访问的url地址' http://localhost:3000/xxxx
 *    }
 */
app.post("/xxx", upload.single("avatar"), (req, res) => {
  console.log("req.file", req.file);
  // 兼容处理
  if (!req.file) {
    res.send({
      code: -1,
      msg: "文件格式不正确",
    });
    return;
  }

  // 将当前的文件移动到 public 文件夹中，并且加个后缀。

  // 读文件
  const fileData = fs.readFileSync(req.file.path, "binary");

  // 写文件
  //  0. 构建文件名
  const fileName = req.file.filename + req.file.originalname;
  //  1. 构建文件路径
  const filePath = path.resolve(__dirname, "./public", fileName);

  console.log(filePath, "===filePath===");
  fs.writeFileSync(filePath, fileData, "binary");

  res.send({
    code: 0,
    msg: "上传成功",
    data: `http://localhost:3000/${fileName}`,
  });
});

app.listen(3000, () => {
  console.log("服务启动成功");
});
